package com.gzz.orchid.common.core.validation.validator;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Retention(RUNTIME)
//指定验证器
@Constraint(validatedBy = CheckMobile.Validator.class)
@Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, CONSTRUCTOR, TYPE_USE})
public @interface CheckMobile {
    String message() default "手机号格式错误";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Slf4j
    class Validator implements ConstraintValidator<CheckMobile, String> {
        private static final String REGEX = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$";

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            boolean result = false;
            try {
                result = Pattern.matches(REGEX, value);
            } catch (Exception e) {
                log.error("验证手机号格式时发生异常，异常信息：", e);
            }
            return result;
        }
    }
}
